const constraints = {
    'video' : true,
    'audio' : true
}
const jsonTemplate = {
    type :"默认",
    data : null,
    sender_id : "默认用户",
    target : "默认接收",
    load : null,
    
};
let localStream;
let peerConnection;
const signalingServer = new WebSocket('ws://' + '116.205.185.181:8000' + '/ws/connection-test/');
// 'ws://' + '116.205.185.181:8000' + '/ws/connection-test/'
// 初始化本地媒体流

function add_chat(type ,str){
    var div = document.createElement("div");
    switch(type) {
        case "enter":
            div.style.color = "#ace6fc";
            div.innerHTML =  str;
            break ;
        case  "leave" :
            div.style.color = "#ace6fc";
            div.innerHTML = str ;
            break;
        case "offer":
            div.style.color = "#fcacb1";
            div.innerHTML = str ;
            break;
        case "cadidate":
            div.style.color = "#1f7025";
            div.innerHTML = str ;
            break;
        case "answer":
            div.style.color = "#e79a55";
            div.innerHTML = str ;
            break;
        case "text":
            div.style.color = "#000000";
            div.innerHTML = str ;
            break;
        case "reply":
            div.style.color = "#FF0000";
            div.innerHTML = str ;
            break;
         }   
    document.body.appendChild(div);
}
async function initMedia() {
    try {
        localStream = await navigator.mediaDevices.getUserMedia(constraints);
        document.querySelector("#local-video").srcObject = localStream;
    } catch (err) {
        console.error('获取媒体设备失败:', err);
    }
}

function createPeerConnection() {
    const config = { 
        iceServers: [{
            urls: "stun:116.205.185.181:3478",
            "username": "text",
            "credential": "123456"
            },  {
            urls: "stun:116.205.185.181:3478"
            }
        ]
      };
    peerConnection = new RTCPeerConnection(config);

    // 添加本地流到连接
    localStream.getTracks().forEach(track => {
        peerConnection.addTrack(track, localStream);
    });

    // ICE 候选收集
    peerConnection.onicecandidate = ({ candidate }) => {
        if (candidate) {
            signalingServer.send(JSON.stringify({
                type: 'candidate',
                candidate: candidate.toJSON()
            }));
        }
    };

    // 接收远程流
    peerConnection.ontrack = event => {
        document.getElementById('remote-video').srcObject = event.streams[0];
    };
}

// 发起通话
async function begin() {
try{
    createPeerConnection();
    console.log("")
    const offer = await peerConnection.createOffer();
    console.log("offer create success");
    await peerConnection.setLocalDescription(offer);
    console.log("offer create success");
    console.log('Offer SDP:', offer.sdp);
    signalingServer.send(JSON.stringify({
        type: 'offer',
        sdp: offer.sdp
    }));
    console.log("offer send");
}
catch{
    console.error("发送 Offer 失败:", error);
}
}

// 信令服务器消息处理
signalingServer.onmessage = async (message) => {
    const data = JSON.parse(message.data);
    
    switch (data.type) {
        case 'offer':
            createPeerConnection();
            await peerConnection.setRemoteDescription(new RTCSessionDescription(data));
            const answer = await peerConnection.createAnswer();
            await peerConnection.setLocalDescription(answer);
            signalingServer.send(JSON.stringify({
                type: 'answer',
                sdp: answer.sdp
            }));
            break;
            
        case 'answer':
            await peerConnection.setRemoteDescription(new RTCSessionDescription(data));
            break;
            
        case 'candidate':
            if (peerConnection) {
                peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
            }
            break;
        case 'text':
            add_chat('text',data.data);
            console.log(data);
            break;
        case 'enter':
            add_chat('enter',data.data);
            console.log(data);
            break;
        case 'reply':
            add_chat('reply',data.reply)
            break;
    }
};
document.querySelector("#button_open").addEventListener("click",initMedia);
document.querySelector('#begin').addEventListener("click",begin);
// 初始化
// initMedia();